/**
 * 发送短信操作类
 **/
package net.tycmc.bulb.note.core.handler.DAO;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.dao.BaseDAO;
import net.tycmc.bulb.common.dao.TransactionDAO;
import net.tycmc.bulb.common.datasource.Connectionable;
import net.tycmc.bulb.common.datasource.ProxoolDataSource;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.bulb.note.core.Util.DateList;
import net.tycmc.bulb.note.core.Util.NoteIndexUtil;
import net.tycmc.bulb.note.core.handler.MyBaseDAO;
import net.tycmc.bulb.note.core.handler.MyTransactionDAO;
import net.tycmc.bulb.note.core.handler.NoteTypeenum;
import net.tycmc.bulb.note.core.handler.SMSConfigenum;
import net.tycmc.bulb.note.core.handler.SMSContentCfg;
import net.tycmc.bulb.note.core.handler.SMSTypeenum;

import org.apache.log4j.Logger;

import com.tycmc.functions.MapFunction;
public class SMSSendDAO {
	private static Logger loger = Logger.getLogger(SMSSendDAO.class);
	private Map<String,Object> checkMap = null;//标志
	private MyBaseDAO myBaseDAO;
	private MyTransactionDAO myTranDAO;
	private SMSLastDAO smsLast;
	public SMSSendDAO(boolean isGcic){
		if(true==isGcic){
			myBaseDAO=new MyBaseDAO();
			BaseDAO baseDAO = new BaseDAO();
			ProxoolDataSource connGetter = new ProxoolDataSource();
			connGetter.setProxoolname("proxool.GcicDateBase");
			baseDAO.setConnGetter(connGetter);
			this.myBaseDAO.setBaseDAO(baseDAO);
			myTranDAO=new MyTransactionDAO();
			TransactionDAO tranDAO = new TransactionDAO();
			ProxoolDataSource connGetterTran = new ProxoolDataSource();
			connGetterTran.setProxoolname("proxool.GcicDateBase");
			tranDAO.setConnGetter((Connectionable)connGetterTran);
			this.myTranDAO.setTranDAO(tranDAO);
			this.smsLast = new SMSLastDAO();
			this.smsLast.setMyBaseDAO(myBaseDAO);
		}else{
			this.myBaseDAO=new MyBaseDAO();
			this.myTranDAO=new MyTransactionDAO();
			this.smsLast = new SMSLastDAO();
		}
	}
	/**
	 * 发送短信
	 **/
	public boolean sendSMS(Map<String,Object> smsMap) {
		boolean flag = false;
		if(null!= smsMap.get("smsType")){/*smsType 定义sms类型具体定义请参阅SMSTypeenum**/
			String  smsType = smsMap.get("smsType").toString();
			//获取短信接收人,故障相关的 、其他类型的
			List<Map<String,Object>> usersList = this.getSMSUsers(smsMap,smsType.equals(String.valueOf(SMSTypeenum.smsFlt.getSmsType())));
			
			if(null!= usersList && usersList.size()>0){
				//判断noteType时，故障需要使用是否有服务人，此步骤必须在getNoteType 之前 
				if(smsType.equals(String.valueOf(SMSTypeenum.smsFlt.getSmsType()))){
					if(null!=usersList){
						for(Map<String,Object> u : usersList){
							if(MapGetter.getString(u, "SMSAS_IsServer").equals("true")){
								smsMap.put("ServerUserName", MapGetter.getString(u, "UserName"));
								smsMap.put("ServerMobile", MapGetter.getString(u, "Mobile"));
								smsMap.put("HaveServer", "true");
								break;
							}
						}
					}
				}
				
				//信息类型——1：故障、2：解除故障、3：故障短信（服务）、4：解除故障（服务）、5：故障12小时报警、6：报警、7：解除报警、8：服务期报警、9：自动安装、10：门控报警、11：传感器报警、12：解除传感器报警、13：进出围栏提示、14：保养提示
				smsMap.put("NoteType", String.valueOf(this.getNoteType(smsMap)));
								
				//统一配置的短信发送时间  SMSCfgType_   SMS_Config的SC_Type
				List<String> sendTime = this.querySMSCfgSendTime(MapGetter.getString(smsMap,"SMSCfgType"));
				//发送标志，比如故障半小时内重复的不发送
				Map<String,Object> half = this.smsLast.checkSendSMSOfHalfHours(smsMap);
				boolean sendFlag = (Boolean)half.get("flag");
				if(null != half.get("param")){
					this.checkMap = (Map<String,Object>)half.get("param"); 
				}
				
				if(sendFlag){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
					if(smsType.equals(String.valueOf(SMSTypeenum.smsFlt.getSmsType()))){//故障时
						flag = this.sendSMSFlt(usersList,smsMap,sendTime);
					}else{
						//因为故障以外的短信发送时间都是统一配置的，所以发送短信的下个工作日校验放在此处，
						Map<String,Object> nextDay = this.smsLast.checkSendSMSOfNextWorkDay(smsMap, sendTime);
						sendFlag = (Boolean)nextDay.get("flag");
						if(null != nextDay.get("param")){
							this.checkMap = (Map<String,Object>)nextDay.get("param"); 
						}
						if(sendFlag){
							flag = this.sendSMSExceptFlt(usersList,smsMap,sendTime);
						}
					}
				}
			}
		}
		return flag;
	}
	/**
	 * 信息类型
	 **/
	private int getNoteType(Map<String, Object> smsMap) {
		int noteType = 0;
		String  smsType = smsMap.get("smsType").toString();
		if(smsType.equals(String.valueOf(SMSTypeenum.smsFlt.getSmsType()))){//故障
			boolean server = MapGetter.getString(smsMap, "HaveServer").equals("true");
			//线性故障
			if(MapGetter.getString(smsMap, "MsgFltType").equals("0")){
				if(server){
					noteType = NoteTypeenum.noteFltServe.getNoteType();
				}else{
					noteType = NoteTypeenum.noteFlt.getNoteType();
				}
			}else{//非线性故障
				noteType = NoteTypeenum.noteFltRelease.getNoteType();
			}
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsAlarm.getSmsType()))){//报警
			if(MapGetter.getString(smsMap, "MsgAlmIsAlarm").equals("1")){
				noteType = NoteTypeenum.noteAlarm.getNoteType();
			}else{
				noteType = NoteTypeenum.noteAlarmRelease.getNoteType();
			}
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsSensor.getSmsType()))){//传感器报警
			if(MapGetter.getString(smsMap, "MsgAlmIsAlarm").equals("1")){
				noteType = NoteTypeenum.noteSensor.getNoteType();
			}else{
				noteType = NoteTypeenum.noteSensorRelease.getNoteType();
			}
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsGate.getSmsType()))){//门控报警
			noteType = NoteTypeenum.noteGate.getNoteType();
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsIOFen.getSmsType()))){//进出围栏提示
			noteType = NoteTypeenum.noteIOFen.getNoteType();
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsServerLine.getSmsType()))){//服务期报警
			noteType = NoteTypeenum.noteServerLine.getNoteType();
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsAutoInstall.getSmsType()))){//自动安装
			noteType = NoteTypeenum.noteAutoInstallVcl.getNoteType();
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsMaint.getSmsType()))){//保养提示
			noteType = NoteTypeenum.noteMaint.getNoteType();
		}else if(smsType.equals(String.valueOf(SMSTypeenum.smsTankLevel.getSmsType()))){//4.19新增液位传感器报警
			noteType = NoteTypeenum.noteTankLevel.getNoteType();
		}
		return noteType;
	}

	/**
	 * 发送除故障之外的短信
	 **/
	private boolean sendSMSExceptFlt(List<Map<String, Object>> usersList,
			Map<String, Object> smsMap,List<String> sendTime) {
		if(null==sendTime){
			sendTime = new ArrayList<String>();
		}
		boolean flag = false;
		List<String> sqlList = null;
		List<Object[]> paramList = null;
		if(null!=usersList && usersList.size()>0 && null!=smsMap){
			sqlList = new ArrayList<String>();
			paramList = new ArrayList<Object[]>();
			//短信内容
			String SMSContent = this.getSMSContentExceptFlt(smsMap);
			//短信发送时间
			String smsSendTime = this.getSendTimeOfNote(sendTime);
			
			Map<String,Object> oneSMS = new HashMap<String,Object>();
			for(Map<String,Object> user:usersList){
				oneSMS = new HashMap<String,Object>();
				oneSMS.putAll(smsMap);
				oneSMS.put("UserID", MapGetter.getString(user, "UserID"));
				oneSMS.put("UserName", MapGetter.getString(user, "UserName"));
				oneSMS.put("UserMobile", MapGetter.getString(user, "Mobile"));
				oneSMS.put("UserDBCode", MapGetter.getString(user, "UserDBCode"));
				oneSMS.put("UserDBName", MapGetter.getString(user, "UserDBName"));
				oneSMS.put("SMSContent", SMSContent);
				oneSMS.put("SendTime", smsSendTime);
			    this.saveSendNote(sqlList,paramList,oneSMS);
			}
			//更新发送短信最新表
			if(null!=this.checkMap && !this.checkMap.isEmpty()){
				this.checkMap.put("msgtime", MapGetter.getString(smsMap,"MsgAlmTime"));
				this.checkMap.put("sendtime", smsSendTime);
				this.smsLast.updateLastSMSInfo(this.checkMap,Integer.parseInt(MapGetter.getString(smsMap,"NoteType")));
			}else{
				smsMap.put("SendTime",smsSendTime);
				this.smsLast.saveLastSMSInfo(smsMap,Integer.parseInt(MapGetter.getString(smsMap,"NoteType")));
			}
		}
		if(null!= sqlList && null!= paramList && paramList.size() == sqlList.size()){
			flag = this.myTranDAO.getTranDAO().batch(sqlList, paramList);
		}
		return flag;
	}
	/**
	 * 获取故障之外的短信内容
	 **/
	private String getSMSContentExceptFlt(Map<String, Object> smsMap) {
		String reStr = "";
		//noteType 的具体含义请参照  NoteTypeenum.java
		int noteType = 0; 
		if(StringUtil.isValid(MapGetter.getString(smsMap,"NoteType"))){
			noteType = Integer.parseInt(MapGetter.getString(smsMap,"NoteType"));
		}
		switch(noteType){
		case 1:
			break;
		case 2:
			break;
		case 3:
			break;
		case 4:
			break;			
		case 5:
			break;
		case 6:
			reStr = SMSContentCfg.SMSCCfgAlarm.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Date", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"),5)).replaceAll("X_Content", MapGetter.getString(smsMap,"MsgAlmTypeName"));
			break;
		case 7:
			break;
		case 8:
			break;
		case 9:
			break;
		case 10:
			reStr = SMSContentCfg.SMSCCfgGate.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Date", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgTime"), 10));
			break;
		case 11:
			if(MapGetter.getString(smsMap,"MsgAlmTypeID").equals("17")){//温度报警
				reStr = SMSContentCfg.SMSCCfgServiceTemp.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Time", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"),10)).replaceAll("X_temp", MapGetter.getString(smsMap,"MsgAlmContent"));
			}else{
				reStr = SMSContentCfg.SMSCCfgServiceSmoke.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Time", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"),10));
			}
			break;
		case 12:
			if(MapGetter.getString(smsMap,"MsgAlmTypeID").equals("17")){//温度报警
				reStr = SMSContentCfg.SMSCCfgServiceSMTempRem.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Time", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"),10)).replaceAll("X_temp", MapGetter.getString(smsMap,"MsgAlmContent"));
			}else{
				reStr = SMSContentCfg.SMSCCfgServiceSmokeRem.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Time", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"),10));
			}
             break;
		case 13:
			reStr = SMSContentCfg.SMSCCfgIOFen.replaceAll("X_VclNum", MapGetter.getString(smsMap,"VehicleNumber")).replaceAll("X_Date", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgTime"), 2)).replaceAll("X_content", MapGetter.getString(smsMap,"MsgContent"));
			break;
		case 14:
			break;
		case 15:
			if(StringUtil.isValid(MapGetter.getString(smsMap, "VehicleContact")) && StringUtil.isValid(MapGetter.getString(smsMap, "VehicleChargedMobile"))){
				reStr = SMSContentCfg.SMSCCfgTankLevel1.replaceAll("X_VclNum", MapGetter.getString(smsMap, "VehicleNumber")).replaceAll("X_Date", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"), 2)).replaceAll("X_SerName", MapGetter.getString(smsMap, "VehicleContact")).replaceAll("X_SerTel", MapGetter.getString(smsMap, "VehicleChargedMobile"));
			}else{
				reStr = SMSContentCfg.SMSCCfgTankLevel2.replaceAll("X_VclNum", MapGetter.getString(smsMap, "VehicleNumber")).replaceAll("X_Date", DateList.getFormatDate(MapGetter.getString(smsMap, "MsgAlmTime"), 2));
			}
			break;
		default:break;
		}
		return reStr;
	}

	/**
	 * 发送故障短信
	 * @param List<String> sendTime 统一配置的短信发送时间 
	 **/
	private boolean sendSMSFlt(List<Map<String, Object>> usersList,
			Map<String, Object> smsMap,List<String> sendTime) {
		boolean flag = false;
		if(null==sendTime){
			sendTime = new ArrayList<String>();
		}
		List<String> sendTime2 = new ArrayList<String>();
		List<String> sqlList = null;
		List<Object[]> paramList = null;
		if(null!=usersList && null!=smsMap){
			sqlList = new ArrayList<String>();
			paramList = new ArrayList<Object[]>();
			flag = true;
			/*故障信息**/
			String Position = MapGetter.getString(smsMap, "Position");
			String MsgFltLo = MapGetter.getString(smsMap, "MsgFltLo"); 
			String MsgFltLa = MapGetter.getString(smsMap, "MsgFltLa");
			String MsgFltType = MapGetter.getString(smsMap, "MsgFltType");
			String MsgFltTime = MapGetter.getString(smsMap, "MsgFltTime");
			String FaultCode = MapGetter.getString(smsMap, "MsgFltCode");
			String FltContentAbbr = MapGetter.getString(smsMap, "FltContentAbbr");
			String FltRisk = MapGetter.getString(smsMap, "FltRisk");
			String FltColorInfo = MapGetter.getString(smsMap, "FltColorInfo");
			String FltLevel = MapGetter.getString(smsMap, "FltLevel");
			
			/*设备信息**/
			String VehicleChargedMobile=MapGetter.getString(smsMap, "VehicleChargedMobile");//车辆联系人电话
			String VehicleContact = MapGetter.getString(smsMap, "VehicleContact");//车辆联系人
			String ESNNumber = MapGetter.getString(smsMap,"ESNNumber");
			String VehicleNumber = MapGetter.getString(smsMap,"VehicleNumber");
			String OEMName = MapGetter.getString(smsMap, "OEMName");//生产厂家
			String OEMTel = MapGetter.getString(smsMap, "OEMTel");//生产厂家电话
			
			if("无".equals(FltColorInfo) || !StringUtil.isValid(FltColorInfo)){
				FltColorInfo = "其他";
			}
			
			/*Position = Position.replaceAll("省", "").replaceAll("市", "").replaceAll("附近", "").replaceAll(" ", "");
			if(Position.length()>15){
				Position = Position.substring(0, 15);
			}
			if("未知".equals(Position) || !StringUtil.isValid(Position)){
				Position = "暂无位置";
			}
			smsMap.remove("Position");
			smsMap.put("Position", Position);*/
			
			/*提示设定信息**/
			String SMSAS_SMSFltIsRed = "";//实时发送短信故障码—红色故障
			String SMSFC_Type = "";		//类型（1：短信白名单；2：短信过滤；3：实时发送短信）
			String smsFltType = "";		//故障分类
			String smsType = "";//提示类型（1：常规提示；2：服务提示）
			String  SMSContent = "";//短信内容
			String SMSAS_SMSFltSendType="";//短信--故障发送类型（1：统一设置；2：单独设置）
			boolean isSer = MapGetter.getString(smsMap, "HaveServer").equals("true")?true:false;
			//设备服务人
			String serName = MapGetter.getString(smsMap, "ServerUserName");
			//设备服务电话
			String serTel = MapGetter.getString(smsMap, "ServerMobile");
			
			Map<String,Object> oneSMS = null;
			for(Map<String,Object> user:usersList){
				smsFltType = MapGetter.getString(user, "SMSAS_FltType"); //故障分类（1：故障等级；2：故障颜色）
				SMSAS_SMSFltIsRed = MapGetter.getString(user, "SMSAS_SMSFltIsRed");//实时发送短信故障码—红色故障（1：选中）
				SMSFC_Type = MapGetter.getString(user, "SMSFC_Type"); //类型（1：短信白名单；2：短信过滤；3：实时发送短信）
				smsType = MapGetter.getString(user, "SMSAS_Type");
				SMSAS_SMSFltSendType=MapGetter.getString(user, "SMSAS_SMSFltSendType");//短信--故障发送类型（1：统一设置；2：单独设置）
				//如果是非线性故障，并且user没有定制非线性故障短信时不发送
				if(MsgFltType.equals("1") && !MapGetter.getString(user, "SMSAS_SMSRels").equals("true")){
					continue;
				}else{
					//如果是非线性故障，并且user没有定制非线性故障短信时不发送
					if(SMSFC_Type.equals("2") && (!(smsFltType.equals("2") && SMSAS_SMSFltIsRed.equals("true")&&FltColorInfo.equals(SMSConfigenum.FltCodeRed.getName()))&& !(smsFltType.equals("1") && MapGetter.getString(user, "SMSAS_SMSFltIsFour").equals("true") && FltLevel.equals("4")))){
						continue;
					}
				}
				//短信--故障发送类型（1：统一设置；2：单独设置）
				if(SMSAS_SMSFltSendType.equals("2")){
					sendTime2.add(0, StringUtil.isValid(MapGetter.getString(user, "SMSAS_SMSFltSendBegin")) ? MapGetter.getString(user, "SMSAS_SMSFltSendBegin") + ":00" : SMSConfigenum.SendTime_Bgn.getName());
					sendTime2.add(1, StringUtil.isValid(MapGetter.getString(user, "SMSAS_SMSFltSendEnd")) ? MapGetter.getString(user, "SMSAS_SMSFltSendEnd") + ":00" : SMSConfigenum.SendTime_End.getName());
				}
				//因为故障存在单独设置时间的情况，因此校验下一个工作日发送的逻辑放在了这里
				Map<String,Object> nextDay = new HashMap<String, Object>();
				if(SMSAS_SMSFltSendType.equals("2")){
					nextDay = this.smsLast.checkSendSMSOfNextWorkDay(smsMap, sendTime2);
				}else{
					nextDay = this.smsLast.checkSendSMSOfNextWorkDay(smsMap, sendTime);
				}
				if(null != nextDay.get("param")){
					this.checkMap = (Map<String,Object>)nextDay.get("param"); 
				}
				if((Boolean)nextDay.get("flag")){
				    String smsSendTime = "";
					//实时发送
					if(SMSFC_Type.equals("3") || ((smsFltType.equals("2") && SMSAS_SMSFltIsRed.equals("true") && FltColorInfo.equals(SMSConfigenum.FltCodeRed.getName()))
							|| (smsFltType.equals("1") && MapGetter.getString(user, "SMSAS_SMSFltIsFour").equals("true") && FltLevel.equals("4")))){	
						smsSendTime = "null";
					}else if(SMSFC_Type.equals("1") || ( smsFltType.equals("2") && (MapGetter.getString(user, "SMSAS_SMSFltRed").equals(FltColorInfo) || MapGetter.getString(user, "SMSAS_SMSFltYellow").equals(FltColorInfo) 
							|| (MapGetter.getString(user, "SMSAS_SMSFltOther").equals("其他") && !FltColorInfo.equals("黄色")&& !FltColorInfo.equals("红色"))))
							|| ( smsFltType.equals("1") && ((MapGetter.getString(user, "SMSAS_SMSFltOne").equals("true")&&FltLevel.equals("1")) || (MapGetter.getString(user, "SMSAS_SMSFltTwo").equals("true")&&FltLevel.equals("2")) 
							|| (MapGetter.getString(user, "SMSAS_SMSFltThree").equals("true")&&FltLevel.equals("3")) || (MapGetter.getString(user, "SMSAS_SMSFltFour").equals("true")&&FltLevel.equals("4"))))){
						if(SMSAS_SMSFltSendType.equals("2")){
							smsSendTime = this.getSendTimeOfNote(sendTime2);
						}else{
							smsSendTime = this.getSendTimeOfNote(sendTime);
						}
					}
					if(StringUtil.isValid(smsSendTime)){
						//线性故障
						if(MsgFltType.equals("0")){
							if(smsType.equals("1")){
								if(isSer == true){
									SMSContent = SMSContentCfg.SMSCCfgFlt1.replace("X_VclNum", VehicleNumber).replace("X_ESNN",ESNNumber).replace("X_Date", DateList.getFormatDate(MsgFltTime, 11)).replace("X_Color",FltColorInfo)
											.replace("X_FltCode", FaultCode).replace("X_FltMsgAbbr", FltContentAbbr).replaceAll("X_Risk", FltRisk)
											.replace("X_SerName", serName).replace("X_SerTel", serTel);
								}else{
									SMSContent = SMSContentCfg.SMSCCfgFlt2.replace("X_VclNum", VehicleNumber).replace("X_ESNN",ESNNumber).replace("X_Date", DateList.getFormatDate(MsgFltTime, 11)).replace("X_Color",FltColorInfo)
											.replace("X_FltCode", FaultCode).replace("X_FltMsgAbbr", FltContentAbbr).replaceAll("X_Risk", FltRisk)
											.replace("X_Factory", OEMName).replace("X_OEMTel", OEMTel);
								}
							}else if(smsType.equals("2")){
								try {
									Position = MapFunction.getPositionReviseNoReplaceDescription(MsgFltLo, MsgFltLa);
								} catch (Exception e) {
									
								}
								Position = Position.replaceAll("省", "").replaceAll("市", "").replaceAll("附近", "").replaceAll(" ", "");
								if(Position.length()>15){
									Position = Position.substring(0, 15);
								}
								if("未知".equals(Position) || !StringUtil.isValid(Position)){
									Position = "暂无位置";
								}
								smsMap.remove("Position");
								smsMap.put("Position", Position);
								SMSContent = SMSContentCfg.SMSCCfgFlt3.replace("X_VclNum", VehicleNumber).replace("X_ESNN",ESNNumber).replace("X_Date", DateList.getFormatDate(MsgFltTime, 11)).replace("X_Color",FltColorInfo)
										.replace("X_FltCode", FaultCode).replace("X_FltMsgAbbr", FltContentAbbr).replaceAll("X_Risk", FltRisk)
										.replace("X_Position", Position).replace("X_SerName", VehicleContact).replace("X_SerTel", VehicleChargedMobile);
							}
						}else{//非线性故障
							SMSContent = SMSContentCfg.SMSCCfgFltRels.replace("X_VclNum", VehicleNumber).replace("X_Date", DateList.getFormatDate(MsgFltTime, 7))
									.replace("X_FltCode", FaultCode);
						}
						oneSMS = new HashMap<String,Object>();
						oneSMS.putAll(smsMap);
						oneSMS.put("UserID", MapGetter.getString(user, "UserID"));
						oneSMS.put("UserName", MapGetter.getString(user, "UserName"));
						oneSMS.put("UserMobile", MapGetter.getString(user, "Mobile"));
						oneSMS.put("UserDBCode", MapGetter.getString(user, "UserDBCode"));
						oneSMS.put("UserDBName", MapGetter.getString(user, "UserDBName"));
						oneSMS.put("SMSContent", SMSContent);
						oneSMS.put("SendTime", smsSendTime);
						this.saveSendNote(sqlList,paramList,oneSMS);
						//更新发送短信最新表
						if(null!=this.checkMap && !this.checkMap.isEmpty()){
							this.checkMap.put("msgtime", MapGetter.getString(smsMap,"MsgFltTime"));
							this.checkMap.put("sendtime", smsSendTime);
							this.smsLast.updateLastSMSInfo(this.checkMap,Integer.parseInt(MapGetter.getString(smsMap,"NoteType")));
						}else{
							if(smsMap.containsKey("SendTime")){
								smsMap.remove("SendTime");
							}
							smsMap.put("SendTime", smsSendTime);
							this.smsLast.saveLastSMSInfo(smsMap,Integer.parseInt(MapGetter.getString(smsMap,"NoteType")));
						}	
					}
				}
			}
		}
		if(null!= sqlList && sqlList.size()>0 && null!= paramList && paramList.size() == sqlList.size()){
			flag = this.myTranDAO.getTranDAO().batch(sqlList, paramList);
		}
		return flag;
	}
	/**
	 * 入库（消息通知系列表、短信队列）
	 **/
	private void saveSendNote(List<String> sqlList, List<Object[]> paramList,
			Map<String, Object> smsMap) {
		int noteType = Integer.parseInt(MapGetter.getString(smsMap,"NoteType"));
		String sql = "";
		Object[] param = null;
		NoteIndexUtil noteUtil = new NoteIndexUtil();		
		sql = "insert into #tablename# (@_VclID,@_SType,@_State,@_MsgContent,@_Position,@_UserID,@_UserName,@_UserDBCode,@_UserDBName,@_Mobile,@_SendTime)" +
				" values(?,1,?,?,?,?,?,?,?,?,"+(MapGetter.getString(smsMap, "SendTime").equalsIgnoreCase("null")?"GETDATE()":MapGetter.getString(smsMap, "SendTime"))+");";
		param = new Object[]{
				MapGetter.getString(smsMap, "VehicleID"),
				MapGetter.getString(smsMap, "noteState"),//故障、机械报警、传感器报警 时报警状态1-报警中，0-已解除
				MapGetter.getString(smsMap, "SMSContent"),
				MapGetter.getString(smsMap, "Position"),
				MapGetter.getString(smsMap, "UserID"),
				MapGetter.getString(smsMap, "UserName"),
				MapGetter.getString(smsMap, "UserDBCode").substring(0,MapGetter.getString(smsMap, "UserDBCode").length()-1),
				MapGetter.getString(smsMap, "UserDBName").substring(0,MapGetter.getString(smsMap, "UserDBName").length()-1),
				MapGetter.getString(smsMap, "UserMobile")
		};
		if(sql.length()>0){
			sql = sql.replaceAll("#tablename#",noteUtil.getNoteTableName(noteType)).replaceAll("@", noteUtil.getNoteTableShort(noteType));
			sqlList.add(sql);
		}
		if(null!=param){
			paramList.add(param);
		}
		//短信队列
		String sendSMS = "insert into SubTransQueue (OrderNumber,SourceNumber,MessageContent,TransportResult,TimingSendTime) values(?,?,?,?,"+(MapGetter.getString(smsMap, "SendTime").equals("null")?"null":MapGetter.getString(smsMap, "SendTime"))+");";
		sqlList.add(sendSMS);
		paramList.add(new Object[] {
			MapGetter.getString(smsMap, "UserMobile"),
			SMSConfigenum.SourceNumber.getName(),
			MapGetter.getString(smsMap, "SMSContent"), 
			"-1"
			});
	}

	/**
	 * 获得短信发送时间
	 */
	private String getSendTimeOfNote(List<String> smsSendTimeList) {
		String sendTime = "null";
		try {
			String SC_SendTime_Bgn = smsSendTimeList.get(0);
			String SC_SendTime_End = smsSendTimeList.get(1);
			long nowTimel = DateUtil.now().getTime();
			long beginl = DateUtil.toDate(
					DateUtil.toString(DateUtil.now(), "yyyy-MM-dd") + " "
							+ SC_SendTime_Bgn, "yyyy-MM-dd HH:mm:ss").getTime();
			long endl = DateUtil.toDate(
					DateUtil.toString(DateUtil.now(), "yyyy-MM-dd") + " "
							+ SC_SendTime_End, "yyyy-MM-dd HH:mm:ss").getTime();
			// 发送规则
			if (beginl <= nowTimel && nowTimel <= endl) {
				sendTime = "null";
			} else if (beginl > nowTimel) {
				sendTime = "'"+DateUtil.toString(DateUtil.now(), "yyyy-MM-dd")+" "+SC_SendTime_Bgn+"'";
			} else {
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, 1);
				sendTime = "'"+DateUtil.toString(calendar.getTime(), "yyyy-MM-dd")+" "+SC_SendTime_Bgn+"'";
			}
		} catch (Exception e) {
			
		}
		return sendTime;
	}
	/**
	 * 查询统一配置配置的短信发送时间
	 * 
	 * @param SC_Type：短信类型 1：电控故障短信；2：保养计划提醒短信；3：日报告；4：机械报警；5：司机行为；6：载重监控；7：故障解除；8：服务期；9：门控报警；10：怠速提醒；11：故障预警；12：烟度报警；13：烟度解除；14：温度报警；15：温度解除；16：进出围栏提示；17：时效预警
	 * @return
	 */
	private List<String> querySMSCfgSendTime(String SC_Type) {
		String sql = "select * from SMS_Config where SC_Type=?";
		Map<String, Object> hm = this.myBaseDAO.getBaseDAO().execQueryOne(sql,
				new Object[] { SC_Type });
		String SC_SendTime_Bgn = hm.get("SC_SendTime_Bgn") != null ? hm.get(
				"SC_SendTime_Bgn").toString()
				+ ":00" : SMSConfigenum.SendTime_Bgn.getName();
		String SC_SendTime_End = hm.get("SC_SendTime_End") != null ? hm.get(
				"SC_SendTime_End").toString()
				+ ":00" : SMSConfigenum.SendTime_End.getName();
		List<String> list = new ArrayList<String>();
		list.add(SC_SendTime_Bgn);
		list.add(SC_SendTime_End);
		return list;
	}
	/**
	 * 查询短信接收人列表
	 **/
	private List<Map<String, Object>> getSMSUsers(Map<String, Object> smsMap,
			boolean fltType) {
		if(fltType){//故障				
			return this.getSMSUsersFlt(smsMap);
		}else{
			return this.getSMSUsersExceptFlt(smsMap);
		}
	}

	/**
	 * 获取故障信息需要发送短信的人员信息
	 **/
	private List<Map<String, Object>> getSMSUsersFlt(Map<String, Object> smsMap) {
		String FltCode = null != smsMap.get("FltCode")?smsMap.get("FltCode").toString():"";
		String DBCode =  null != smsMap.get("DBCode")?smsMap.get("DBCode").toString():"";
		String VehicleID =  null != smsMap.get("VehicleID")?smsMap.get("VehicleID").toString():"";
		String sql = "select distinct awb.aob_openid as openid,awb.aob_accountid as accountid,SMSAS_ID,ui.UserID,ui.UserName,ui.Mobile,ui.Email,ui.organizationcode as UserDBCode,ui.organizationname as UserDBName,smsas.SMSAS_SMSAtt, "
			+"smsfc.SMSFC_Type,SMSAS_SMSFltIsRed,SMSAS_SMSFltSendType,case SMSAS_SMSFltRed when 1 then '红色' else NULL end SMSAS_SMSFltRed, "
			+"case SMSAS_SMSFltYellow when 1 then '黄色' else NULL end SMSAS_SMSFltYellow, "
			+"case SMSAS_SMSFltOther when 1 then '其他' else NULL end SMSAS_SMSFltOther,SMSAS_SMSRels, "
			+"SMSAS_SMSFltSendBegin,SMSAS_SMSFltSendEnd "
			+",SMSAS_Type,SMSAS_IsServer,SMSAS_FltType,SMSAS_SMSFltFour,SMSAS_SMSFltThree,SMSAS_SMSFltTwo,SMSAS_SMSFltOne,SMSAS_SMSFltIsFour "
			+",SMSAS_SMAFlttw "
			+"from SMS_Alarm_SetInfo as smsas "    	
			+"inner Join v_userInfo_Organization_all as ui ON smsas.SMSAS_UsP_ID=ui.UserID and ui.usefullife>getdate() "
			+"inner join (select  userid  from userinfoaccount u inner join v_userinfo_organization uu on u.UserOrganizationID = uu.UserOrganizationID where UsefulLife > getdate()  group by userid) tb on tb.userid = ui.UserID "
			+"left join AccountWeichatBang as awb on awb.aob_userid = ui.userid and awb.aob_releasetime>GETDATE() "
			+"left join SMSDB on smsas.SMSAS_ID=SMSDB_SMSAS_ID "
			+"left join SMSVcl on smsas.SMSAS_ID=SMSVcl_SMSAS_ID "
			+"left join (select SMSFC_SMSAS_ID,MAX(SMSFC_Type) as SMSFC_Type " 
			+"from SMSFltCode where SMSFC_FltCode=? group by SMSFC_SMSAS_ID) smsfc on smsfc.SMSFC_SMSAS_ID=smsas.SMSAS_ID "
			+"where ((smsas.SMSAS_SMSAtt=1  and SMSDB_DBCode=?) or (smsas.SMSAS_SMSAtt=2 and SMSVcl_VehicleID=? )) "
			+"and (SMSFC_Type is not null or SMSAS_SMSFltIsRed=1 or SMSAS_SMSFltRed=1 or SMSAS_SMSFltYellow=1 or SMSAS_SMSFltOther=1 or SMSAS_SMSFltFour = 1 or SMSAS_SMSFltThree = 1 or SMSAS_SMSFltTwo = 1 or SMSAS_SMSFltOne = 1 or SMSAS_SMSFltIsFour = 1) and awb.aob_openid is null ";
		List<Map<String,Object>> list = this.myBaseDAO.getBaseDAO().execQuery(sql, new Object[]{FltCode,DBCode,VehicleID});
		return list;
	}
	/**
	 * 获取故障信息以外的信息需要发送短信的人员信息
	 **/
	private List<Map<String, Object>> getSMSUsersExceptFlt(Map<String, Object> param) {
		String MadeType = null!=param.get("MadeType")?param.get("MadeType").toString():"";
		StringBuffer sql = new StringBuffer("select distinct SMSAS_ID,ui.UserID,ui.UserName,ui.Mobile,ui.Email,ui.organizationcode as UserDBCode,ui.organizationname as UserDBName,smsas.SMSAS_SMSAtt ");
		sql.append("from SMS_Alarm_SetInfo as smsas ");
		sql.append("inner Join v_userInfo_Organization_all as ui ON smsas.SMSAS_UsP_ID=ui.UserID and ui.usefullife>getdate() ");
		sql.append("inner join (select  userid  from userinfoaccount u inner join v_userinfo_organization uu on u.UserOrganizationID = uu.UserOrganizationID where UsefulLife > getdate()  group by userid) tb on tb.userid = ui.UserID ");
		sql.append("left join SMSDB on smsas.SMSAS_ID=SMSDB_SMSAS_ID  ");
		sql.append("left join SMSVcl on smsas.SMSAS_ID=SMSVcl_SMSAS_ID where 1=1 ");
		if(null!=param.get("DBCode") && null!= param.get("VehicleID")){
			sql.append("and ((smsas.SMSAS_SMSAtt=1 and SMSDB_DBCode= '"+param.get("DBCode").toString()+"') or (smsas.SMSAS_SMSAtt=2 and SMSVcl_VehicleID= '"+param.get("VehicleID").toString()+"')) ");
		}else if(null!=param.get("DBCode") && null == param.get("VehicleID")){
			sql.append("and (smsas.SMSAS_SMSAtt=1 and SMSDB_DBCode='"+param.get("DBCode").toString()+"') ");
		}else if(null!=param.get("VehicleID") && null == param.get("DBCode")){
			sql.append("and (smsas.SMSAS_SMSAtt=1 and SMSDB_DBCode='"+param.get("VehicleID").toString()+"') ");
		}
		if(MadeType.length()>0){
			sql.append(" and UsefulLife>=GETDATE() and isnull(ui.mobile,'')<>'' and isnull(ui.OrganizationCode,'')<>'' and smsas."+MadeType+"=1 ");
		}
		return this.myBaseDAO.getBaseDAO().execQuery(sql.toString(), new Object[]{});
	}
}
